package pw.goyd.db;

import pw.goyd.game.manager.GameManager;
import pw.goyd.game.server.Log;
import pw.goyd.subscribe.BinaryRedisPubSubListener;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import java.util.Scanner;

/**
 * Created by StanWind on 2016/10/21.
 * 远程全局消息推送
 */
public class MsgTerminal {
    public static void main(String[] args) {
        RedisUtil.init();                               //  Redis 订阅初始化
        packerListener();                               //  当前控制台的消息接受
        Scanner sc = new Scanner(System.in);            //  接收键盘输入
        System.out.printf("格式---->0#msg\n");          //   输入提示
        while (sc.hasNext()) {                          //  循环输入
            String temp = sc.nextLine();
            String msg[] = temp.split("#");             //  分割#作为命令
            if (msg.length == 2) {                      //  msg for broadcast
                if (msg[0].equals("-1")) {              //  roomID == -1 broadcast
                    //GameManager.sendAnnounceMsg(msg[1]);  客户端加了时间验证 所以不能在这个实例发消息
                    RedisUtil.publishData("Announce".getBytes(), temp.getBytes());

                } else {                                // msg for room
                    int roomID = Integer.valueOf(msg[0]);
                    RedisUtil.publishData("Announce".getBytes(), temp.getBytes());
                    RedisUtil.publishData("MsgTerminal".getBytes(), ("" + roomID).getBytes());
                }
            } else {
                System.out.printf("消息格式错误 length---->" + msg.length + "\n");    //Error
            }
        }
    }

    public static void packerListener() {
        // 新建一个Listener 为redisclient监听订阅
        BinaryRedisPubSubListener listener = new BinaryRedisPubSubListener();
        Jedis client = RedisUtil.getJedis();    //  从池中获取
        // 阻塞监听线程
        Thread msgTerTh;
        msgTerTh = new Thread(() -> {
            try {
                Log.getLogger().info("Packer is Listening");
                client.psubscribe(listener,
                        ("Packer").getBytes());
            } catch (JedisException e) {
                Log.getLogger().error(e.toString());
            } catch (ClassCastException e) {
                Log.getLogger().error(
                        "B cannot be cast to java.util.List");
            }
        });
        msgTerTh.start();
    }

}
